﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;
using System.ServiceModel;
using PW.DBCommon.Dao;
using PW.DBCommon.Model;

namespace PW.SecurityWcf.Core
{
    public class AuthenticationInspector : IDispatchMessageInspector  
    {
        string[] whiteList = new string[]{
            "IServiceLogin.Login",
        };
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            var context = OperationContext.Current;
            string contractName = context.EndpointDispatcher.ContractName;
            string operationName = string.Empty;
            if (context.IncomingMessageHeaders.Action == null)
            {
                operationName = request.Properties.Values.LastOrDefault().ToString();
            }
            else
            {
                if (context.IncomingMessageHeaders.Action.Contains("/"))
                {
                    operationName = context.IncomingMessageHeaders.Action.Split('/').LastOrDefault();
                 }
            }
            string action = contractName + "." + operationName;
            //注意引用 System.Runtime.Serialization
            if (whiteList.Contains(action)) {
                return null;
            }
           string UserId = request.Headers.GetHeader<string>("UserId", "pw.com");
            //string Password = request.Headers.GetHeader<string>("Password", "pw.com");
            string UserName = request.Headers.GetHeader<string>("UserName", "pw.com");
            // string Token = request.Headers.GetHeader<string>("Token", "pw.com");
            // 暂时查询username是否存在--后期可考虑改为token缓存加有效期
            sys_user user = new SysUserDao().getByUserName(UserName);
            if (user == null)
            {
                // 断开连接
                //request.Close();
                throw (new Exception(String.Format("用户：{0} 不存在", UserName)));
            }
            else if ("2".Equals(user.del_flag))
            {
                throw (new Exception(String.Format("对不起，您的账号：{0} 已被删除", UserName)));
            }
            else if ("1".Equals(user.status))
            {
                throw (new Exception(String.Format("对不起，您的账号：{0} 已停用", UserName)));
            }
            else
            {
                return null;
            }
            //可从后台数据库中进行验证
            /*
            if (UserId != "admin" && Password != "123456")
            {
                throw new Exception("用户名和密码不正确！");
            }
             */
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
        }
    }
}